package com.hjy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hjy.common.domain.response.GoodsRes;
import com.hjy.common.result.Goods;
import com.hjy.common.result.PageResult;
import com.hjy.common.utils.StringUtils;
import com.hjy.service.EsService;
import com.hjy.user.mapper.EsMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EsServiceImpl implements EsService {
    @Autowired
    private EsMapper esMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    private static final String INDEX_NAME = "goods";
    /**
     * 添加
     */
    @Override
    public void addGoods(List<GoodsRes> goodsList) {
        BulkRequest bulkRequest = new BulkRequest();
        goodsList.forEach(goods -> {
           bulkRequest.add(new IndexRequest(INDEX_NAME)
                   .id(goods.getId()+"")
                   .source(JSONObject.toJSONString(goods), XContentType.JSON));
        });
        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 删除
     */
    @Override
    public void fiandDel() {
        DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_NAME);
        request.setQuery(QueryBuilders.matchAllQuery());
        try {
            restHighLevelClient.deleteByQuery(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 搜索
     *
     * @return
     */
    @Override
    public PageResult<Goods> selGoods(Goods goods) {
        long total = 0L;
        List<Goods> list = new ArrayList<>();
        try {
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);

        SearchSourceBuilder builder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isNotBlank(goods.getGoodsName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("goodsName",goods.getGoodsName()));
        }
        builder.query(boolQueryBuilder);
        builder.from((goods.getPageNum()-1)*goods.getPageSize());
        builder.size(goods.getPageSize());
        builder.highlighter(new HighlightBuilder().field("goodsName")
                .preTags("<span style='color:red'>").postTags("</span>"));
        searchRequest.source(builder);

        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        total = hits.getTotalHits().value;
            SearchHit[] hits1 = hits.getHits();

            for (SearchHit documentFields : hits1) {
                String sourceAsString = documentFields.getSourceAsString();

                Goods goods1 = JSONObject.parseObject(sourceAsString, Goods.class);

                Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
                if (highlightFields!=null){
                    HighlightField highlightField = highlightFields.get("goodsName");
                    if (highlightField!=null){
                        String str = "";
                        Text[] fragments = highlightField.fragments();
                        if (fragments!=null){
                            str += fragments;
                        }
                        goods1.setGoodsName(str);
                    }
                }

                list.add(goods1);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return PageResult.toPageResult(total,list);
    }
}
